package demo2;

import java.io.*;
import java.security.interfaces.DSAKey;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-11
 * Time: 22:33
 */
public class InputStream_OutputStream {
    //无参数read()
    public static void main1(String[] args){
        try(InputStream inputStream = new FileInputStream("./aaa/bbb/ccc/a.text")) {
            while (true) {
                //无参数read方法的返回值是无符号整数
                //这保证所有的字节值可以被精确表示，避免溢出变成负数
                //所以ret的范围是0~255
                //当读取到最后一个字节后，再次读取会返回-1
                int ret = inputStream.read();
                if (ret == -1) {
                    break;
                }
                System.out.printf("%x ", ret);
                //e4 b9 9d e8 bd ac e8 8b 8d e7 bf 8e
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //参数传入字节数组read((byte b[])
    public static void main(String[] args){
        try(InputStream inputStream = new FileInputStream("./aaa/bbb/ccc/a.text")) {
            byte[] array = new byte[40];
            //无参数read方法的返回值是有符号整数
            int ret = inputStream.read(array);
            /*System.out.println(Arrays.toString(array));*/
            for (int i = 0; i < ret; i++) {
                System.out.printf("%x ", array[i]);
                //e4 b9 9d e8 bd ac e8 8b 8d e7 bf 8e
            }
            System.out.println();
            System.out.println(new String(array, 0, ret));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main3(String[] args) {
        try(InputStream inputStream = new FileInputStream("./aaa/bbb/ccc/a.text")) {
            byte[] array = new byte[40];
            //无参数read方法的返回值是有符号整数
            int ret = inputStream.read(array,1,12);
            /*System.out.println(Arrays.toString(array));*/
            for (int i = 0; i < ret; i++) {
                System.out.printf("%x ", array[i]);
                //e4 b9 9d e8 bd ac e8 8b 8d e7 bf 8e
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //
    public static void main4(String[] args) {
        try(OutputStream outputStream = new FileOutputStream("./aaa/bbb/ccc/a.text",true)){
            outputStream.write(97);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
